package factorytest.iflytek.com.einkiflytekfactorytest.common;

import android.content.Context;
import android.os.UserHandle;
import android.provider.Settings;
import android.util.Log;

/**
 * 20181124: 控制 EINK 前光。我们在背光的基础上进行扩展。
 */
public class ForeLightCtrl {

    /*
     * 20181127: 最大背光改为 63(0X3F),这样每个背光用 6BIT 来表示。冷光和暖光就不会丢失信息了。
     */

    private static final int FLIGHT_COLD_SHIFT = 6;
    public static final int MAX_BRIGHTNESS = ((1 << FLIGHT_COLD_SHIFT) - 1);

//	Context			mContext;
//	PowerManager	mPowerManager;

    private int mWarmLightBrightness = 0;
    private int mColdLightBrightness = 0;
    private static ForeLightCtrl mInstance;


    private ForeLightCtrl() {  //Context ctx
//		mContext = ctx;
//		mPowerManager = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
    }

    // 20181204: avoid multi thread access.
    public static ForeLightCtrl getForeLightCtrl() {
        synchronized (ForeLightCtrl.class) {
            if (mInstance == null) {
                mInstance = new ForeLightCtrl();
            }
            return mInstance;
        }
    }

    private void setComposeBackLight(Context ctx) {
        // 20181126：为了解决休眠唤醒后背光值不能变化的问题，我们采用 BIT_MASK的方式设置背光。
        int brightness = mWarmLightBrightness + (mColdLightBrightness << FLIGHT_COLD_SHIFT);
        Log.d("ForeLightCtrl", "setComposeBackLight=" + brightness + ",cold=" +
                mColdLightBrightness + ",warm=" + mWarmLightBrightness);
        // 20181202:采用这种方式，可以在 不修改 PMS 的情况下，把设置的亮度值保存下来。
//		mPowerManager.setBacklightBrightness(brightness);
        Settings.System.putInt(ctx.getContentResolver(),
//                Settings.System.SCREEN_BRIGHTNESS,
//                Settings.System.SCREEN_BRIGHTNESS_FOR_VR,
                "screen_brightness_for_vr",
                brightness
        );
    }

    /**
     * 设置前置暖光灯的亮度，范围是 从  0...MAX_BRIGHTNESS，需要 系统签名的权限。
     *
     * @param brightness
     */
    public void setWarmLightBrightness(Context ctx, int brightness) {
        if (brightness < 0) {
            brightness = 0;
        } else if (brightness > MAX_BRIGHTNESS) {
            brightness = MAX_BRIGHTNESS;
        }
        mWarmLightBrightness = brightness;
        setComposeBackLight(ctx);
    }

    public int getWarmLightBrightness() {
        return mWarmLightBrightness;
    }

    /**
     * 设置前置冷光灯的亮度，范围是 从  0...MAX_BRIGHTNESS，需要 系统签名的权限。
     *
     * @param brightness
     */
    public void setColdLightBrightness(Context ctx, int brightness) {
        if (brightness < 0) {
            brightness = 0;
        } else if (brightness > MAX_BRIGHTNESS) {
            brightness = MAX_BRIGHTNESS;
        }
        mColdLightBrightness = brightness;
        setComposeBackLight(ctx);
    }

    public int getColdLightBrightness() {
        return mColdLightBrightness;
    }

    public int getMaxBrightness() {
        return MAX_BRIGHTNESS;
    }
}
